<?php

namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Model\CanvassBusiness;
use Illuminate\Http\Request;

/**
 * 招商加盟
 * Class CanvassBusinessController
 * @package App\Http\Controllers\Back
 */
class CanvassBusinessController extends Controller
{
    public function list(Request $request)
    {
        $obj = new CanvassBusiness();
        $query = $obj
            ->orderBy('created_at','desc');


        if ($name  = $request->query('name')){
            $query = $query->where('name', 'like',"%$name%");
        }

        if ($phone  = $request->query('phone')){
            $query = $query->where('phone', 'like',"%$phone%");
        }

        if ($type  = $request->query('type')){
            $query = $query->where('type', $type);
        }

        if ($province_id  = $request->query('province_id')){
            $query = $query->where('province_id', $province_id);
        }
        if ($start_time  = $request->query('start_time')){
            $query = $query->where('created_at', '>=', $start_time);
        }
        if ($end_time  = $request->query('end_time')){
            $query = $query->where('created_at', '<=', $end_time);
        }

        $per_page = $request->query('per_page', 20);


        $query = $query->leftJoin('places', 'places.id' , '=', 'canvass_business.province_id');
        $query = $query->leftJoin('places as city', 'city.id' , '=', 'canvass_business.city_id');
        $query = $query->select(['city.name as c_name','places.name as p_name','canvass_business.name', 'canvass_business.phone', 'canvass_business.province_id', 'canvass_business.city_id', 'canvass_business.area_id', 'canvass_business.type', 'canvass_business.created_at']);

        $canvassMsg = $query->paginate($per_page);

        $data = $canvassMsg->toArray();

        return $this->renderJson([
            'list' => $data['data'],
            'pagination' => [
                'current' => $canvassMsg->currentPage(),
                'per_page' => $per_page,
                'total' => (int)ceil($canvassMsg->total() / $per_page),
                'count' => $canvassMsg->total()
            ]
        ]);
    }
}